package com.ptswitch.material.pages.visitor;

import javax.servlet.http.HttpServletResponse;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.project.AppRuntimeException;
import org.slf4j.Logger;

import com.ptswitch.material.model.common.LoginInfo;
import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.LoginInfoService;
import com.ptswitch.material.service.UserService;
import com.ptswitch.material.util.WebUtil;
import com.ptswitch.material.util.security.RoleUtil;

public class Login extends PageBase {

    @Inject
    private LoginInfoService loginInfoSer;
    @Inject
    private UserService userSer;
    @Property
    private Uzer user;
    @Property
    private String redirectPath;
    @Inject
    private Logger logger;

    @Inject
    private HttpServletResponse response;

    public Object withInit(String redirectPath) {
        init(redirectPath);
        return this;
    }

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init() {
        user = new Uzer();
        return null;
    }

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init(String redirectPath) {
        user = new Uzer();
        this.redirectPath = redirectPath;
        return null;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return redirectPath;
    }

    @OnEvent(value = EventConstants.SUCCESS)
    //, component = "login" error for t5.3.7,when logined
    Object login() {
        if (userSer.countAll() == 0) {
            user.md5password();
            user.setRealname(user.getUsername());
            user.addRole(RoleUtil.Admin);
            userSer.save(user);
        }
        //
        Uzer visitor = userSer.findByUsernameAndPassword(user.getUsername(), user.getPassword());
        if (visitor == null) {
            throw AppRuntimeException.error("登录失败，用户名或密码错误");
        }
        loginInfoSer.deleteByUsername(visitor.getUsername());
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUser(visitor);
        loginInfoSer.save(loginInfo);
        response.addCookie(WebUtil.addUsernameCookie(loginInfo.getUsername()));
        response.addCookie(WebUtil.addLoginTokenCookie(loginInfo.getId()));
        logger.info("user login:{}", loginInfo.getUsername());
//		if (redirectPath != null) {
//			return redirectPath;
//		}
        return null;
    }

}
